from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from orders.views import MyAlipay
import redis
from orders.models import Order
from django.shortcuts import redirect

class CheckPayResult(MyAlipay):

    # 删除redis购物车中已购买的商品
    def delete_buied_good(self, order):
        # 6.删除redis购物车中的已下订单的商品
        redis_conn = redis.Redis(host='localhost', port=6379, db=0, password='123')
        cart_key = "cart:%s" % order.user.id
        cart_selected_key = "cart_selected:%s" % order.user.id

        # 查询所有订单商品
        products_list = order.ordergood_set.all()
        for i in products_list:
            redis_conn.hdel(cart_key, i.good_id)
            redis_conn.srem(cart_selected_key, i.good_id)

        redis_conn.close()

    # 接受GET请求 return_url回调
    def get(self,request):
        # 查看支付的相关参数
        print("支付参数", request.query_params)

        # 获取订单编号
        order_id = request.query_params.get("out_trade_no")
        print("订单:", order_id)
        # 主动查询支付结果
        pay_result = self.alipay.api_alipay_trade_query(order_id)
        # 根据oder_id查询order对象
        order = Order.objects.get(order_id=order_id)
        # 获取支付状态
        trade_status = pay_result.get('trade_status')
        if trade_status == "TRADE_SUCCESS":
            # 支付成功
            status = 1
            # 删除购物车中已购买的商品
            self.delete_buied_good(order)

            # 更改订单的状态
            order.pay_status = '1'
            order.save()

        else:
            # 支付失败
            status = 0


        # return Response({'code':200, 'msg':'支付成功' if status else "支付失败"})
        return redirect("http://localhost:8080/#/order")

    # 接受支付宝的异步通知POST 请求
    def post(self, request):

        # 接受支付的结果数据
        pay_result = request.data

        # 判断是否支付宝发来的请求
        sign = pay_result.pop("sign")
        validation = self.alipay.verify(pay_result, sign)

        if validation:
            # 是支付宝发的请求
            if pay_result.get("trade_status") == "TRADE_SUCCESS":
                # 支付成功

                # 删除购物车中已购买的商品
                # self.delete_buied_good()
                return HttpResponse("success")

        else:
            # 不是支付宝的请求
            return Response({"code":204, 'msg':'非法的请求'})


    # 接受 订单支付的 put 请求
    def put(self,request):
        # 1.获取前端数据
        order_id = request.data.get("orderID")
        total_amount = request.data.get("totalPrice")

        # 2.生成支付地址
        pay_url = self.get_pay_url(order_id, total_amount)


        # 3.返回响应
        return Response({"code":302,'msg':'正在跳转支付地址···', 'pay_url':pay_url})












